#!/bin/bash
#功能: 停tomcat, 用tomcat原有shutdown.sh，检查pid是否已停止, 轮询APP_SLEEP_NUM次, 每次sleep APP_SLEEP_TIME秒, 若仍未停止则调用kill -9处理该进程。
#      tomcat工作目录: ./env.conf中TOMCAT_BIN配置当前tomcat工作目录
#      端口号: ${TOMCAT_BIN}/../conf/service.xml中配置的Connector port xxxxxx protocol="HTTP/XXXXX"
#      进程id: 通过lsof -i:端口号, 查找当前tomcat进程id
#
#注意项:
#      1. service.xml中Connector port如果有需要注释的情况, Connector port行必须有注释标签“<!--"，该行不能跨行注释
#      2. 若tomcat出现异常，Connector port端口已经不监听了但tomcat进程还在, 本shell将获取不到tomcat的pid，需手工处理
#
#返回值:
#      0 - 成功
#      2 - tomcat端口不在监听在状态
#      else - 其他错误

APP_SLEEP_NUM=30
APP_SLEEP_TIME=1


echo "##########start boar-deploy-web_stop.sh##########"

is_stop()
{
        if [ "$1" == "" ]; then
                echo "[ERROR]: pid is null, please input process id"
                return 1
        fi

        local cur_num
        local pid=$1
        for ((i=0; i<${APP_SLEEP_NUM}; i++))
        do
                cur_num=1
                cur_num=`ps -ef |awk '$2=='"$pid"' {print}' |wc -l`
                is_suc "ps -ef |awk 'pid==$pid {print}' |wc -l"
                if [ ${cur_num} -eq 0 ]; then
                        echo "pid[${pid}] is stopped"
                        return 0
                fi

                echo "stop [${APP_SLEEP_TIME}], please wait..."
                sleep ${APP_SLEEP_TIME}
        done

        echo "sleep ${APP_SLEEP_NUM}*${APP_SLEEP_TIME} second, pid[$1] unable to stop, please check !!!"
        return 1
}

#加载环境变量
env_path=`dirname $0`
. ${env_path}/env.conf

ret=`grep "Connector port" ${TOMCAT_BIN}/../conf/server.xml |grep "HTTP" |grep -v '<!--' |awk -F'[="]' '{print $3}' |wc -l`
is_suc "get Connector port"
if [[ "${ret}" != "1" ]]; then
        echo "[ERROR]: get tomcat port num[$ret]"
        exit 1
fi
port=`grep "Connector port" ${TOMCAT_BIN}/../conf/server.xml |grep "HTTP" |grep -v '<!--' |awk -F'[="]' '{print $3}'`
echo "[INFO]: tomcat prot[$port]"

echo "lsof -i:${port} |awk '/java/ {print $2}' |wc -l"
pid_num=`lsof -i:${port} |awk '/java/ {print $2}' |wc -l`
is_suc "get tomcat pid num"
echo "[DEBUG]: get tomcat pid num[${pid_num}]"
if [[ "${pid_num}" != "1" ]]; then
        echo "[ERROR]: tomcat pid num[${pid_num}]"
        if [[ "${pid_num}" == "0" ]]; then
                exit 2
        fi

        exit 1
fi
pid=`lsof -i:${port} |awk '/java/ {print $2}'`
echo "[INFO]: tomcat pid[$pid]"

cd ${TOMCAT_BIN}
is_suc "cd ${TOMCAT_BIN}"

sh shutdown.sh
is_suc "exec shutdown.sh"

is_stop ${pid}
#is_suc "is_stop [${pid}]"
ret=$?
if [[ "$ret" != "0" ]]; then
        echo "[DEBUG]: start kill -9 [${pid}]"
        kill -9 ${pid}
        is_suc "kill -9 ${pid}"
else
        echo "[INFO]: s_stop [${pid}] suc"
fi


echo "##########boar-deploy-web_stop.sh SUC##########"
exit 0